<?php
namespace app\index\controller;

use think\Request;
use think\Session;

class Agent extends Common{

	//代理邀请
    public function invite(){
		
		$response = \ServerHelper::post('agentinvite_level_list',['agentid'=>AGENT_ID]);
		$data = $this->J($response);
		if(empty($data['flag'])){
			__log('agent invite：'.$response,'agent');
			exit;
		}
		return view('',$data['data']);
    }
	//根据邀请的代理级别 生成推广链接
	public function invite_create(){
		$request = Request::instance();
		
		$idstr = $request->param('levels');
		if(!preg_match('/^[0-9a-zA-Z_]+(,[0-9a-zA-Z_]+)*$/',$idstr)){
			$this->error('参数错误');
		}
		
		$response = \ServerHelper::post('agentinvite_result_code',['agentid'=>AGENT_ID]);
		$data = $this->J($response);
		if(empty($data['flag'])){
			__log('agent invite create：'.$response,'agent');
			exit;
		}
		$invite_url = $request->domain() . '/?inviterid='. AGENT_ID .'&levels=' . $idstr;
		$data['data']['invite_url'] = base64_encode($invite_url);
		
		//微信配置
		$response = \ServerHelper::post('GetWeChatConfig');
		$response = json_decode($response,true);
		if(empty($response['appid'])){
			$this->error('数据错误');
		}
		$hp = new \WechatBase($response['appid'],$response['appsecret']);
		$param = $hp->getSignPackage();
		$data['data']['wx'] = $param;

		return view('',$data['data']);
	}
	
	//邀请注册推广码
	public function invitecode(){
		$data = Request::instance()->param('data');
		$data = base64_decode($data);
		Vendor('phpqrcode.phpqrcode');
		\QRcode::png($data);
	}
	
	//代理审核列表
	public function invite_list(){
		$req = Request::instance();
		$pm = [
			'agentid' => AGENT_ID,
			'status' => $req->param('status',-1,'intval'),
			'page' => $req->param('page',1,'intval')
		];
		$res = \ServerHelper::post('agent_invite_check',$pm);
		$data = $this->J($res);
		return view('',$data['data']);
	}
	
	//我的升级记录详情
	public function upgrade_detail(){
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => Request::instance()->param('orderid')
		];
		$response = \ServerHelper::post('upgrade_detail',$param);
		$data = $this->J($response);
		return view('',$data['data']);
	}
	
	//我要升级
	public function upgrade(){
		$param = [
			'agentid' => AGENT_ID
		];
		$response = \ServerHelper::post('agentupgrade_upgrade_show',$param);
		$data = $this->J($response);
		/*
		0：可升级
		1：待资料审核（上级或者总部）
		2: 申请等级审核（上级或者总部）
		3：资料审核完成，待付货款
		4：已付货款，待审核（如不需要付货款，跳转到6）
		5：已付货款，审核失败
		6：货款审核完成，待付保证金（如果不需要增加保证金，跳9）
		7：已付保证金，待审核
		8：已付保证金，审核失败
		9：升级完成（更新等级，更新进货上级）
		-1：升级驳回/取消升级
		*/
		if($data['data']['status'] == 0){
			return view('',$data['data']);
		}else if($data['data']['status'] == 1){
			//等待上级审核第一步
			return view('upgrade_ing',$data['data']);
		}else if($data['data']['status'] == 2){
			//上级通过了资料的审核
			return view('upgrade_ing',$data['data']);
		}else if($data['data']['status'] == 3){
			//上级通过了目标代理等级的审核，等待我付货款
			return view('upgrade_ing',$data['data']);
		}else if($data['data']['status'] == 4){
			//已付货款，待审核
			return view('upgrade_ing',$data['data']);
		}else if($data['data']['status'] == 5){
			echo '5';
		}else if($data['data']['status'] == 6){
			//上级通过了货款审核，等待我付保证金
			return view('upgrade_ing',$data['data']);
		}else if($data['data']['status'] == 7){
			//已付保证金、待审核
			return view('upgrade_ing',$data['data']);
		}else if($data['data']['status'] == 8){
		}else if($data['data']['status'] == 9){
			//升级成功
			
		}
		//var_dump($data);
		return view('upgrade_ing',$data['data']);
	}
	
	//自己升级。选择打款方式
	public function upgrade_pay_show(){
		$request = Request::instance();
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => $request->param('orderid'),
			'ordertype' => $request->param('ordertype') //orderamount=货款充值;deposit=保证金充值
		];
		$response = \ServerHelper::post('upgrade_pay_show',$param);
		$data = $this->J($response);
		
		if($param['ordertype'] == 'orderamount'){
			$data['data']['title'] = '货款充值';
		}else{
			$data['data']['title'] = '保证金充值';
		}
		return view('',$data['data']);
		
	}
	//自己升级，线下支付
	public function upgrade_xxpay(){
		$request = Request::instance();
		if($request->isPost()){
			$postdata = [
				'agentid' => AGENT_ID,
				'orderid' => $request->param('orderid'),
				'ordertype' => $request->param('ordertype'),
				'paytype' => 1,
				'amount' => $request->param('amount'),
				'repaccounttype' => $request->param('repaccounttype'),
				'repaccount' => $request->param('repaccount'),
				'remark' => $request->param('remark'),
			];
			$reppicture = $request->param('reppicture');
			if($postdata['repaccounttype'] == '' || $postdata['repaccount'] == ''){
				$this->error('请选择收款人账户');
			}
			$arr = explode(',',$reppicture);
			if(count($arr) < 1 || substr($arr[0],0,4) != 'http'){
				$this->error('请上传打款凭证');
			}
			$postdata['reppicture'] = json_encode($arr);
			
			$response = \ServerHelper::post('upgrade_xxpay_do',$postdata);
			$response = $this->J($response);
			if($response['flag']){
				$this->success('提交成功，请等待审核',url('Agent/upgrade'));
			}else{
				$this->error($response['msg']);
			}
			
		}else{
			$param = [
				'agentid' => AGENT_ID,
				'orderid' => $request->param('orderid'),
				'ordertype' => $request->param('ordertype') //orderamount=货款充值;deposit=保证金充值
			];
			$response = \ServerHelper::post('upgrade_xxpay_show',$param);
			$data = $this->J($response);
			$data['data']['orderid'] = $param['orderid'];
			$data['data']['ordertype'] = $param['ordertype'];

			//选择数据
			$accountType = [];
			$accountTypeFull = [];
			if(isset($data['data']['repaccount']['wechat'])){
				$accountType[] = [
					'id'=>$data['data']['repaccount']['wechat']['accountid'],
					'value'=>$data['data']['repaccount']['wechat']['accountname'],
				];
				$accountTypeFull['wechat'] = [
					'id'=>$data['data']['repaccount']['wechat']['accountid'],
					'value'=>$data['data']['repaccount']['wechat']['accountname'],
				];
			}
			if(isset($data['data']['repaccount']['alipay'])){
				$accountType[] = [
					'id'=>$data['data']['repaccount']['alipay']['accountid'],
					'value'=>$data['data']['repaccount']['alipay']['accountname'],
				];
				$accountTypeFull['alipay'] = [
					'id'=>$data['data']['repaccount']['alipay']['accountid'],
					'value'=>$data['data']['repaccount']['alipay']['accountname'],
				];
			}
			if(isset($data['data']['repaccount']['bank'])){
				$accountType[] = [
					'id'=>$data['data']['repaccount']['bank']['accountid'],
					'value'=>$data['data']['repaccount']['bank']['accountname'],
				];
				$accountTypeFull['bank'] = [
					'id'=>$data['data']['repaccount']['bank']['accountid'],
					'value'=>$data['data']['repaccount']['bank']['accountname'],
				];
			}
			$data['data']['accounttype'] = json_encode($accountType,JSON_UNESCAPED_UNICODE);
			$data['data']['accounttypefull'] = json_encode($accountTypeFull,JSON_UNESCAPED_UNICODE);
			return view('',$data);
		}
	}
	
	//升级微信支付
	public function upgrade_wepay(){
		$ordertype = Request::instance()->param('ordertype'); //订单类型(付哪一个步骤)
		$amount = Request::instance()->param('amount'); 
		$paytype = PAYTYPE_WEIXIN; //支付类型、微信
		$orderid = Request::instance()->param('orderid');
		
		if($ordertype  == ''){
			$this->error('参数错误');
		}
		
		//拉取支付信息
		$request = [
			'agentid' => AGENT_ID,
			'ordertype' => $ordertype,
			'paytype' => $paytype,
			'amount' => $amount,
		];
		$payinfo = \ServerHelper::post('recharge_wepay_show',$request);
		$payinfo = $this->J($payinfo);
		if($payinfo['flag'] != 1){ $this->error('支付发起失败'); }

		$param = [
			'body' => $payinfo['data']['products'],
			'orderid' => $payinfo['data']['orderid'],
			'pay_no' => $payinfo['data']['payid'],
			'price' => intval($payinfo['data']['amount']), //价格(单位：分)
			'notify_url' => Request::instance()->domain() . url('Agent/upgrade_notify_url'),
		];
		
		Vendor('weixinpay.do.JSAPI2');
		$hp = new \JSAPI2();
		
		list($jsApiParameters,$editAddress) = $hp->GetParam($param['body'],$param['pay_no'],$param['price'],$param['notify_url']);
		
		return view('',[
			'orderid' => $param['orderid'],
			'jsApiParameters'=>$jsApiParameters,
			'editAddress'=>$editAddress
		]);
	}
	#region 微信支付通知
	public function upgrade_notify_url(){
		Vendor('weixinpay.do.NOTIFY_RECHARGE');
		$hp = new \NOTIFY2();
		$hp->Start('upgrade');
	}
	public function upgrade_return_url(){
		$orderid = Request::instance()->param('orderid');
		//$this->redirect('Order/pay',['orderid'=>$orderid]);
		echo 'result ' . $orderid;
	}
	#endregion
	
	
	//②拉取升级提示信息
	public function upgrade_tip(){
		$request = Request::instance();
		$param = [
			'agentid' => AGENT_ID,
			'target_levelid' => $request->param('level'),
			'upgradetype' => $request->param('type')
		];
		$response = \ServerHelper::post('agentupgrade_upgrade_tip',$param);
		$data = $this->J($response);
		ajax('SUCCESS',true,$data['data']);
	}
	
	//③确认升级信息
	public function upgrade_confirm(){
		$request = Request::instance();
		if($request->isPost()){
			
			$param = [
				'agentid' => AGENT_ID,
				'target_levelid' => $request->param('level'),
				'upgradetype' => $request->param('type'),
				'upgradetypemsg' => $request->param('typemsg'),
				'orderid' => $request->param('orderid'),
				'idnumber' => $request->param('idnumber'),
				'wechatid' => $request->param('wechatid'),
				'sex' => $request->param('sex'),
			];
			$response = \ServerHelper::post('upgrade_confirm_do',$param);
			$data = $this->J($response);
			
			ajax($data['msg'],$data['flag'] == 1);
		}else{
			$param = [
				'agentid' => AGENT_ID,
				'target_levelid' => $request->param('level'),
				'upgradetype' => $request->param('type'),
				'orderid' => $request->param('orderid'),
			];
			$response = \ServerHelper::post('upgrade_confirm_show',$param);
			$data = $this->J($response);
			$info = [
				'level' => $param['target_levelid'],
				'type' => $param['upgradetype'],
				'typemsg' => $request->param('typemsg'),
			];
			return view('',[
				'data' => $data['data'],
				'info' => $info
			]);
		}
	}
	
	//取消我的升级
	public function upgrade_cancel(){
		$request = Request::instance();
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => $request->param('orderid'),
		];
		$response = \ServerHelper::post('upgrade_cancel',$param);
		$data = $this->J($response);
		ajax($data['msg'],$data['flag'] == 1);
	}
	
	
	//我的升级记录
	public function upgrade_list(){
		
		$menu = [
			1=>'升级中',
			2=>'已完成',
			3=>'已关闭'
		];
		
		$req = Request::instance();
		$pm = [
			'agentid' => AGENT_ID,
			'status' => $req->param('status'),
		];
		if(!array_key_exists($pm['status'],$menu)){
			$pm['status'] = 1;
			
		}
		$res = \ServerHelper::post('upgrade_list_of_mine',$pm);
		$data = $this->J($res);
		$data['menu'] = $menu;
		$data['status'] = $pm['status'];
		return view('',$data);
	}
	
	//下级正在升级记录
	public function subupgrade(){
		$req = Request::instance();
		$status = $req->param('status',1);
		$pm = [
			'agentid' => AGENT_ID,
			'status' => $status
		];
		$res = \ServerHelper::post('subupgrade_list',$pm);
		$data = $this->J($res);
		if(empty($data['data']['list'])){
			$data['data']['list'] = [];
		}
		if(empty($data['data']['subupgradenum'])){
			$data['data']['subupgradenum'] = 0;
		}
		return view('',$data);
	}
	
	//下级代理升级记录
	public function subupgrade_list(){
		$menu = [
			1=>'升级中',
			2=>'已完成',
			3=>'已关闭'
		];
		$req = Request::instance();
		$pm = [
			'agentid' => AGENT_ID,
			'status' => $req->param('status'),
		];
		if(!array_key_exists($pm['status'],$menu)){
			$pm['status'] = 1;
		}
		$res = \ServerHelper::post('subupgrade_list',$pm);
		$data = $this->J($res);
		if(empty($data['data']['list'])){
			$data['data']['list'] = [];
		}
		if(empty($data['data']['subupgradenum'])){
			$data['data']['subupgradenum'] = 0;
		}
		$data['menu'] = $menu;
		$data['status'] = $pm['status'];
		
		return view('',$data);
	}
	
	//下级升级详情
	public function subupgrade_detail(){
		$param = [
			'agentid' => AGENT_ID,
			'orderid' => Request::instance()->param('orderid')
		];
		$response = \ServerHelper::post('subupgrade_detail',$param);
		$data = $this->J($response);
		return view('',$data['data']);
	}
	
	//下级升级的身份信息、代理等级信息
	public function subupgrade_check(){
		$req = Request::instance();
		$act = $req->param('act');
		if($act == 'sfsh_no'){
			//拒绝身份申请
			$pm = [
				'orderid' => $req->param('orderid'),
				'agentid' => AGENT_ID,
				'checktype' => 1, //1、资料 2、等级
				'checkresult' => 0,//1通过
				'remark' => $req->param('remark')
			];
			if($pm['remark'] == ''){
				ajax('请输入驳回原因');
			}
			$res = \ServerHelper::post('subupgrade_check_do',$pm);
			$data = $this->J($res);
			ajax($data['msg'],$data['flag'] == 1);
			
		}else if($act == 'sfsh_yes'){
			//身份通过
			$pm = [
				'orderid' => $req->param('orderid'),
				'agentid' => AGENT_ID,
				'checktype' => 1, //1、资料 2、等级
				'checkresult' => 1,//1通过
				'remark' => $req->param('remark')
			];
			$res = \ServerHelper::post('subupgrade_check_do',$pm);
			$data = $this->J($res);
			ajax($data['msg'],$data['flag'] == 1);
		}else if($act == 'dengji_yes'){
			//等级通过
			$pm = [
				'orderid' => $req->param('orderid'),
				'agentid' => AGENT_ID,
				'checktype' => 2, //1、资料 2、等级
				'checkresult' => 1,//1通过
			];
			$res = \ServerHelper::post('subupgrade_check_do',$pm);
			$data = $this->J($res);
			ajax($data['msg'],$data['flag'] == 1);
		}else if($act == 'dengji_no'){
			//等级不通过
			$pm = [
				'orderid' => $req->param('orderid'),
				'agentid' => AGENT_ID,
				'checktype' => 2, //1、资料 2、等级
				'checkresult' => 0,//1通过
			];
			$res = \ServerHelper::post('subupgrade_check_do',$pm);
			$data = $this->J($res);
			ajax($data['msg'],$data['flag'] == 1);
		}else{
			//拉取身份信息
			$pm = [
				'orderid' => $req->param('orderid'),
				'subagentid' => $req->param('subagentid'),
				'agentid' => AGENT_ID
			];
			$res = \ServerHelper::post('subupgrade_shenfen_check_show',$pm);
			$data = $this->J($res);
			$data['data']['subagent']['tiaojian'] = $data['data']['UpgradeConditions'];
			if(empty($data['flag'])){
				ajax($data['msg']);
			}else{
				ajax('SUCCESS',true,$data['data']['subagent']);
			}
		}
	}
	
	//下级充值订单列表
	public function suborders(){
		$request = Request::instance();
		$status = $request->param('status','1','intval');
		$page = $request->param('page','1','intval');
		$response = \ServerHelper::post('agent_suborders',[
			'agentid' => AGENT_ID,
			'status' => $status,
			'page' => $page
		]);
		$data = $this->J($response);
		$list = [];
		foreach((array)$data['data']['list'] as $v){
			$list[] = [
				'rechargeid' => $v['充值单号'],
				'agentname' => $v['充值代理'],
				'rechargetype' => $v['充值类别'],
				'rechargetime' => $v['充值时间'],
				'status' => $v['审核状态'],
			];
		}
		$data['data']['list'] = $list;
		return view('',$data['data']);
	}
	//下级充值订单分页
	public function suborders_loadpage(){
		$request = Request::instance();
		$status = $request->param('status','-1','intval');
		$page = $request->param('page','1','intval');
		$response = \ServerHelper::post('agent_suborders',[
			'agentid' => AGENT_ID,
			'status' => $status,
			'page' => $page
		]);
		$data = $this->J($response);
		$list = [];
		foreach((array)$data['data']['list'] as $v){
			$list[] = [
				'rechargeid' => $v['充值单号'],
				'agentname' => $v['充值代理'],
				'rechargetype' => $v['充值类别'],
				'rechargetime' => $v['充值时间'],
				'status' => __agent_suborder_status($v['审核状态']),
				'btns' => __suborder_status_btn($v['审核状态']),
			];
		}
		$data['data']['list'] = $list;
		ajax('SUCCESS',true,$data['data']);
	}
	
	//下级充值订单详情
	public function suborder_detail(){
		$request = Request::instance();
		$rechargeid = $request->param('rechargeid');
		$response = \ServerHelper::post('agent_suborder_detail',[
			'agentid' => AGENT_ID,
			'chargeid' => $rechargeid
		]);
		$data = $this->J($response);
		
		$reward = [
			'chargetype' => $data['data']['reward']['充值类别'],
			'xiajijine' => $data['data']['reward']['下级充值金额'],
			'koukuanjine' => $data['data']['reward']['自身扣款金额'],
		];
		$jiangli = [];
		foreach($data['data']['reward']['奖励信息'] as $v){
			$jiangli[] = [
				'agentname' => $v['被奖励代理姓名'],
				'agentphone' => $v['被奖励代理电话号码'],
				'agentplevel' => $v['被奖励代理等级名称'],
				'money' => $v['奖励金额'],
				'info' => $v['奖励科目'],
			];
		}
		$reward['jiangli'] = $jiangli;
		$data['data']['reward2'] = $reward;
		
		return view('',$data);
	}
	
	//下级充值订单审核动作
	public function suborder_check(){
		$request = Request::instance();
		$rechargeid = $request->param('rechargeid');

		$param = [
			'agentid' => AGENT_ID,
			'chargeid' => $rechargeid,
		];
		$act = $request->param('act');
		if($act == 'confirm'){
			$param['res'] = 1;
			$param['pwd'] = $request->param('info');
		}else{
			$param['res'] = 2;
			$param['remark'] = $request->param('info');
		}
		
		$response = \ServerHelper::post('agent_suborder_check',$param);
		$data = $this->J($response);
		ajax($data['msg'],$data['flag'] == 1);
	}
	
	
	//微信解绑
	public function unbindwechat(){
		$req = Request::instance();
		if($req->isPost()){
			$pm = [
				'agentid' => AGENT_ID,
			];
			$res = \ServerHelper::post('^/home/unbindwechat',$pm);
			$data = $this->J($res);
			if($data['flag'] == 1){
				Session::delete('wechat_id');
			}
			ajax($data['msg'],$data['flag'] == 1);
		}else{
			return view();
		}
	}

}
